<template>
	<view>
		<view class="user-infor">
			<view class="tit">
				收货地址
			</view>
			<view class="flex-box" @click="goAddr">
				<image class="icon" src="../../static/images/icon43.png" mode="widthFix"></image>
				<view class="left" v-if="addrList.length > 0">
					<view class="t1">
						<!-- {{content.defaultReceiver.consignee}} {{content.defaultReceiver.phone}} -->
						{{showAddr.name}} {{showAddr.phone}}
					</view>
					<view class="t2">
						<!-- {{content.defaultReceiver.areaName}} -->
						{{showAddr.areaName}}
					</view>
				</view>
				<view class="left" v-else>
					<view class="t1">
						<!-- {{content.defaultReceiver.consignee}} {{content.defaultReceiver.phone}} -->
						<!-- {{showAddr.name}} {{showAddr.phone}} -->
						请新增收货地址
					</view>
					<view class="t2">
						<!-- {{content.defaultReceiver.areaName}} -->
						<!-- {{showAddr.areaName}} -->
					</view>
				</view>
				<view class="right"></view>
			</view>

		</view>

		<view class="mid-par">
			<view class="o-list">
				<view class="o-item" v-for="(item,index) in content.cart.cartItems" :key="index" :item-id="index"
					:data-skuid="item.skuId">

					<view class="img"
						:style="{background:img?('url('+baseUrl+ item.sku.product.image.thumbnail +') center no-repeat'):'',backgroundSize:'cover'}">

					</view>
					<view class="int">
						<view class="t1">
							{{item.sku.product.name}}
						</view>
						<view class="t2">
							重量：{{item.sku.product.weight}}G
						</view>
						<view class="t3">
							¥{{item.sku.price}}
						</view>
					</view>
					<view class="cp-num">
						<view @click="changeNum(index, item.quantity, 'minus')" class="cut">
							<image :src="item.quantity<=1?'../../static/images/icon-cut.png':'../../static/images/icon-cut1.png'" mode="widthFix"></image>
						</view>
						<view class="num">{{item.quantity}}</view>
						<view @click="changeNum(index, item.quantity, 'add')" class="add">
							<image src="../../static/images/icon-add.png" mode="widthFix"></image>
						</view>
					</view>
				</view>

			</view>
		</view>
		
		<view class="coupon" v-if="content.couponCodes && content.couponCodes.length > 0">
			<view class="item" :class="{on: item.selected}" @click="selectCoupon(item)" v-for="item,index in content.couponCodes" :key="index">{{item.coupon.name}}</view>
		</view>

		<view class="order-infor">
			<view class="item" v-if="content.orderType !== 'EXCHANGE'">
				<view class="left">商品总价</view>
				<view class="right">¥ {{content.price}}</view>
			</view>
			<view class="item" v-if="content.orderType !== 'EXCHANGE'">
				<view class="left">店铺优惠 </view>
				<view class="right">¥ {{content.couponDiscount}}</view>
			</view>
			<view class="item" v-if="content.orderType === 'EXCHANGE'">
				<view class="left">商品积分 </view>
				<view class="right"> {{content.exchangePoint}}</view>
			</view>
			<view class="item" v-if="content.fee>0">
				<view class="left">手续费 </view>
				<view class="right">¥ {{content.fee}}</view>
			</view>
			<view class="item" v-if="content.freight>0">
				<view class="left">运费 </view>
				<view class="right">¥ {{content.freight}}</view>
			</view>
			<view class="item">
				<view class="left">合计 </view>
				<view class="right">¥ {{content.amountPayable}}</view>
			</view>
		</view>

		<view class="order-infor">
			<view class="item">
				<view class="left">付款方式 </view>

				<!-- <picker class="right" @change="bindPickerChange" :value="payindex" :range="content.paymentPlugins"
					:range-key="'name'">
					<view class="uni-input">{{content.paymentPlugins[payindex].name}}</view>
				</picker> -->
				<view>微信支付</view>
			</view>
		</view>
		
		<view class="line"></view>
		
		<view class="bottom_total">
			<view class="left">
				<text v-if="content.amountPayable > 0">待支付：¥ {{content.amountPayable}}</text><text v-if="content.orderType === 'EXCHANGE'">积分 {{content.exchangePoint}}</text>
			</view>
			<view class="right" @click="pay">
				立即支付
			</view>
		</view>

	</view>
</template>

<script>
	import {
		checkout,
		create,
		toPay
	} from '@/api/order.js';
	import {
		modifyCart
	} from '@/api/cart.js'
	import {
		getReceiver
	} from '@/api/user.js';
	export default {
		data() {
			return {
				baseUrl: this.$baseUrl,
				img: '../../static/images/cp10.png',
				content: '',
				payindex: 0,
				cartItemIds: '',
				skuId: '',
				quantity: '',
				addrId: '',
				addrList: [],
				showAddr: {},
				couponCodeIds: '',
				couponList: []
			};
		},
		onLoad(option) {
			console.log(option)
			if(option.quantity!=undefined&&option.skuId!=undefined){
				this.quantity = option.quantity;
				this.skuId = option.skuId;
			}
			if(option.id!=undefined){
				this.cartItemIds = option.id;
			}
			// this.init()
		},
		onShow() {
			if(uni.getStorageSync('addrId')) {
				this.addrId = uni.getStorageSync('addrId')
			}
			this.init()
			this.initAddr()
		},
		onUnload() {
			uni.setStorageSync('addrId', '')
			uni.setStorageSync('selectCouponIds', '')
		},
		methods: {
			init() {
				checkout({
					cartItemIds:this.cartItemIds,
					skuId: this.skuId,
					quantity: this.quantity,
					couponCodeIds: this.couponCodeIds
				}).then(res => {
					console.log(res)
					let selectCouponIds = ''
					if(uni.getStorageSync('selectCouponIds')) {
						selectCouponIds = uni.getStorageSync('selectCouponIds')
					}
					this.content = res.data
					this.couponList = this.content.couponCodes
					this.couponList.forEach(r => {
						if(selectCouponIds === r.id) {
							r.selected = true
						} else {
							r.selected = false
						}
					})
				}).catch((err) => {
					// setTimeout(() => {
					// 	uni.navigateBack()
					// }, 1000)
				})
			},
			initAddr() {
				getReceiver().then(res => {
					this.addrList = res.data.receiverList
					this.addrList.some(r => {
						if(this.addrId !== '') {
							console.log('1', r)
							if(this.addrId == r.id) {
								this.showAddr = r
								return true
							}
						} else {
							if(r.isDefault) {
								this.showAddr = r
								return true
							}
						}
					})
				})
			},
			changeNum(index, i, type) {
				if(type === 'add') {
					i++
					this.doChangeNum(index, i)
				} else {
					if(i >= 2) {
						i--
						this.doChangeNum(index, i)
					}
				}
			},
			selectCoupon(item) {
				// item.selected = !item.selected
				// this.couponCodeIds = ''
				// this.couponList.forEach(r => {
				// 	if(r.selected) {
				// 		this.couponCodeIds += r.id + ','
				// 	}
				// })
				let id = ''
				this.couponList.forEach(r => {
					if(item.id === r.id) {
						if(r.selected) {
							r.selected = false
						} else {
							r.selected = true
							id = r.id
						}
					} else {
						r.selected = false
					}
				})
				this.couponCodeIds = id
				uni.setStorageSync('selectCouponIds', this.couponCodeIds)
				this.init()
			},
			doChangeNum(index, i) {
				let skuId = this.content.cart.cartItems[index].sku.id
				if(this.content.cart.cartItems[index].id === null) {
					this.quantity = i
					this.init()
				} else {
					modifyCart({skuId, quantity: i}).then(res => {
						this.init()
					})
				}
			},
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.payindex = e.detail.value
				this.paymentMethodId = this.content.paymentPlugins[this.payindex].id
			},
			goAddr() {
				uni.navigateTo({
					url: '/pages/site/site?choose=true'
				})
			},
			pay() {
				// skuId 规格id（商品立即购买必传, quantity 商品数量（商品立即购买必传,receiverId 收货地址id,
				// paymentMethodId 支付方式id,shippingMethodId 配送方式id
				// couponCodeIds 优惠券项id，多个用逗号隔开
				// cartItemIds 购物车项id，多个用逗号隔开（购物车立即购买必传）
				
				if(!this.showAddr.id) {
					uni.showToast({
						title: '请新增收货地址',
						icon: 'none'
					})
					return
				}

				let payid = this.content.defaultPaymentMethod.id

				let data = {
					cartItemIds: this.cartItemIds,
					// receiverId: this.content.defaultReceiver.id,
					receiverId: this.showAddr.id,
					shippingMethodId: this.content.defaultShippingMethod.id,
					paymentMethodId: payid,
					couponCodeIds: this.couponCodeIds
				}
				
				console.log(data)
				
				if(data.cartItemIds == '') {
					delete data.cartItemIds
					data.skuId = this.skuId
					data.quantity = this.quantity
				}

				create(data).then(res => {
					var openid = uni.getStorageSync('openid');
					if (res.code == 200) {
						if(res.data.amountPayable > 0) {
							toPay({
								paymentPluginId: 'weixinAppletPaymentPlugin',
								orderSns: res.data.orderSns[0],
								openid: openid
							}).then(res => {
								console.log(res)
								if (res.message == '操作成功') {
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: res.data.timeStamp,
										nonceStr: res.data.nonceStr,
										package: res.data.package,
										signType: res.data.signType,
										paySign: res.data.paySign,
										success: function(infoRes) {
											if (infoRes.errMsg == "requestPayment:ok") {
												uni.showToast({
													title: '支付成功',
													duration: 2000,
													icon: 'none'
												})
												uni.redirectTo({
													url: '/pages/order/order?type=PENDING_SHIPMENT'
												})
											}
											console.log('success:' + JSON.stringify(infoRes));
										},
										fail: function(err) {
											// uni.showToast({
											// 	title: err.errMsg,
											// 	icon: 'error'
											// })
											setTimeout(() => {
												uni.navigateTo({
													url: '/pages/order/order?type='
												})
											}, 800)
										}
									});
								}
							})
						} else {
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/order/detail?sn=' + res.data.orderSns[0]
								})
							}, 800)
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
		
	}
	.line{
		width: 100%;
		height: 150rpx;
	}

	.user-infor {
		// padding: 40rpx 20rpx;
		margin-top: 30rpx;
		background-color: #ffffff;

		.tit {
			font-size: 28rpx;
			font-weight: bold;
			padding: 30rpx;
			border-bottom: 1px solid #ebebeb;
		}

		.flex-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 30rpx;

			.icon {
				width: 35rpx;
			}
		}

	}


	.user-infor .left {
		flex: 1;
		width: 100%;

		padding-left: 60rpx;
	}

	.user-infor .left .t1 {
		font-size: 24rpx;
		margin-bottom: 10rpx;
		color: #595757;
	}

	.user-infor .left .t2 {
		font-size: 24rpx;
		color: #595757;
		line-height: 1.5;
	}

	.user-infor .right {
		position: relative;
		margin-left: 120rpx;
	}

	.user-infor .right::after {
		content: '';
		display: block;
		position: absolute;
		border-top: 1px solid #666666;
		border-right: 1px solid #666666;
		transform: rotate(45deg);
		right: 8px;
		width: 10px;
		height: 10px;
	}
	
	.coupon {
		margin-top: 30rpx;
		background-color: #ffffff;
		padding: 30rpx 30rpx 20rpx;
		
		.item {
			line-height: 60rpx;
			padding: 0 15rpx;
			border: 1px solid #ebebeb;
			margin: 0 10rpx 10rpx 0;
			display: inline-block;
		}
		
		.item.on {
			border: 1px solid #b81c22;
		}
	}

	.mid-par {
		margin-top: 30rpx;
		background-color: #ffffff;
		padding: 0 30rpx;

		.o-list {
			.o-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 30rpx 0;

				.img {
					width: 160rpx;
					height: 160rpx;
				}

				.int {
					flex: 1;
					padding: 0 30rpx;

					.t1 {
						font-size: 24rpx;
						color: #1a1a1a;
						margin-bottom: 20rpx;
					}

					.t2 {
						font-size: 28rpx;
						color: #898989;
						margin-bottom: 45rpx;
					}

					.t3 {
						color: #898989;
						font-size: 28rpx;
					}
				}

				.cp-num {
					font-size: 28rpx;
					color: #898989;
					display: flex;
					
					view {
						display: flex;
						width: 50rpx;
						line-height: 50rpx;
						text-align: center;
						align-items: center;
						justify-content: center;
						border: 1px solid #ebebeb;
						
						image {
							width: 16rpx;
						}
					}
				}
			}
		}
	}

	.order-infor {
		background-color: #ffffff;
		padding: 0 30rpx;

		margin-top: 30rpx;
	}

	.order-infor .item {
		border-bottom: 1px solid #f5f5f5;
		padding: 40rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: #1a1a1a;
	}

	.bottom_total {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 110rpx;
		width: 100%;
		background-color: #ffffff;
		position: fixed;
		bottom: 0;
		left: 0;

		.left {
			padding-left: 30rpx;

			text {
				color: #b81c22;
				font-size: 32rpx;
			}
		}

		.right {
			color: #ffffff;
			letter-spacing: 4rpx;
			width: 300rpx;
			text-align: center;
			height: 110rpx;
			line-height: 110rpx;
			background-color: #b81c22;
		}
	}
</style>
